import router from '@/router'
import store from "@/store";
import formatTime from "@/utils/time";
// 禁用今天之后的时间、
import moment from "moment";

// 节流
function debounce(fn, wait) {
  let timeout = null; // 定义一个定时器
  return function() {
    if (timeout !== null) clearTimeout(timeout); // 清除这个定时器
    timeout = setTimeout(fn, wait);
  };
}

// 将以为数组转化成 树形节点 多位数组
function treeBuild(arr) {

  if (!Array.isArray(arr)) {
    return [];
  }
  const copyArr = JSON.parse(JSON.stringify(arr));
  const map = new Map();
  for (let i = 0; i < copyArr.length; i++) {
    map.set(copyArr[i].id, copyArr[i]);
  }
  const treeData = [];
  for (let i = 0; i < copyArr.length; i++) {
    const item = copyArr[i];

    if (item.parentId=='0') {
      treeData.push(item);
      continue;
    }
    const parent = map.get(item.parentId);
    if (parent!='0'&&item.type!=2) {
      if (!Array.isArray(parent.children)) {
        parent.children = [];
      }
      parent.children.push(item);
    }
  }
  return treeData;
}

// 寻找子节点
function findLeafs(arr) {
  const map = new Map();
  for (let i = 0; i < arr.length; i++) {
    map.set(arr[i].ID, arr[i]);
  }
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    if (item.ParentID) {
      delete map.delete(item.ParentID);
    }
  }
  return map;
}

// 获取当前时间 Ymdhis
function getFormatDate() {
  const date = new Date();
  let month = date.getMonth() + 1;
  let strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }

  return `${date.getFullYear()}${month}${strDate}${date.getHours()}${date.getMinutes()}${date.getSeconds()}`;
}

/**
 * [randomStr 生成随机字符串]
 * @return {[String]} [生成好的随机字符串]
 * 1、定义拼接字符串变量
 * 2、定义随机字符串数组
 * 3、遍历随机字符串数组 长度为range
 * 4、返回生成好的字符串
 */
function randomStr(range) {
  let str = "";
  const arr = [
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z"
  ];
  for (let i = 0; i < range; i++) {
    const pos = Math.round(Math.random() * (arr.length - 1));
    str += arr[pos];
  }
  return str;
}

// 将以为数组转化成 树形节点 多位数组   树状节点筛选
function treeBuildS(arr) {
  if (!Array.isArray(arr)) {
    return [];
  }
  const copyArr = JSON.parse(JSON.stringify(arr));
  const map = new Map();
  for (let i = 0; i < copyArr.length; i++) {
    map.set(copyArr[i].id, copyArr[i]);
  }
  const treeData = [];
  for (let i = 0; i < copyArr.length; i++) {
    const item = copyArr[i];
    if (item.p_id == "nil") {
      treeData.push(item);
      continue;
    }
    const parent = map.get(item.p_id);
    if (parent) {
      if (!Array.isArray(parent.children)) {
        parent.children = [];
      }
      parent.children.push(item);
    }
  }
  return treeData;
}

// 格式化时间
function filterDate(date) {
  let dateSt = `${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6, 8)}`;

  let dates = new Date(dateSt).getTime();

  return dates;
}

// 计算 多少年之后
function stringDate(startDate, year) {
  let years = parseInt(year) + parseInt(startDate.slice(0, 4));

  let dateSt = `${years}-${startDate.slice(4, 6)}-${startDate.slice(6, 8)}`;

  let date = new Date(dateSt).getTime();

  return date;
}

// 筛选路由页面
function treeBuildRouter(arr) {
  if (!Array.isArray(arr)) {
    return [];
  }
  // 深拷贝 数据
  const copyArr = JSON.parse(JSON.stringify(arr));
  const map = new Map();
  for (let i = 0; i < copyArr.length; i++) {
    map.set(copyArr[i].ID, copyArr[i]);
  }
  const treeData = [];
  for (let i = 0; i < copyArr.length; i++) {
    const item = copyArr[i];
    if (item.ID && item.Type != 5 && item.FrontendRoute != "") {
      treeData.push(item);
      continue;
    }
  }
  for (let i = 0; i < copyArr.length; i++) {
    // const item = copyArr[i]
    treeData.map(ite => {
      if (ite.ParentID == copyArr[i].ID && ite.Type != 5) {
        ite.ParentName = copyArr[i].Name;
      }
    });
  }
  return treeData;
}

function passwordLevel(val) {
  var level = 0;
  if (val.length < 5) return 0;
  if (/\d/.test(val)) level++; //数字
  if (/[a-z]/.test(val)) level++; //小写
  if (/[A-Z]/.test(val)) level++; //大写
  if (/\W/.test(val)) level++; //特殊字符

  return level;
}

// 提价文件
function fileFilter(fileList) {
  let list = [];
  fileList.map(item => {
    if (item.response != undefined) {
      if (item.response.code == 0) {
        list.push(item.response.data.url);
      }
    } else if (item.status == "done") {
      list.push(item.url);
    }
  });
  let urls = list.join(",");
  return urls;
}

// 格式化文件
function fileDetail(data) {
  let arr = [];
  data.map(ite => {
    let obj = {
      uid: ite.url,
      name: ite.name,
      status: "done",
      url: ite.url
    };
    arr.push(obj);
  });
  return arr;
}

// 格式化签章
function signaturesFilter(list) {
  list.map(items => {
    items.planSignatures.map((item, index) => {
      if (item.signatureType == 0) {
        item.disabled = true;
        item.leable = "激励对象签字";
        item.companyUserId = "";
        item.sort = index;
        item.input = false;
        item.checkbox = false;
        item.type = 2;
        item.signatureType = item.signatureType;
      }
      if (item.signatureType == 1) {
        item.disabled = true;
        item.leable = "出让方签字";
        item.companyUserId = "";
        item.sort = index;
        item.input = false;
        item.checkbox = false;
        item.type = 2;
        item.signatureType = item.signatureType;
      }
      if (item.signatureType == 2) {
        item.disabled = true;
        item.leable = "受让方签字";
        item.companyUserId = "";
        item.sort = index;
        item.input = false;
        item.checkbox = false;
        item.type = 2;
        item.signatureType = item.signatureType;
      }
      if (item.signatureType == 3) {
        item.disabled = false;
        item.leable = "授权代表签字";
        item.companyUserId = "";
        item.sort = index;
        item.input = true;
        item.checkbox = true;
        item.type = 2;
        item.signatureType = item.signatureType;
      }
      if (item.signatureType == 4) {
        item.disabled = false;
        item.leable = "公司盖章";
        item.companyUserId = "";
        item.sort = index;
        item.input = true;
        item.checkbox = true;
        item.type = 1;
        item.signatureType = item.signatureType;
      }
      if (item.signatureType == 5) {
        item.disabled = true;
        item.leable = "被回购方";
        item.companyUserId = "";
        item.sort = index;
        item.input = false;
        item.checkbox = false;
        item.type = 2;
        item.signatureType = item.signatureType;
      }
      if (item.signatureType == 6) {
        item.disabled = true;
        item.leable = "回购方";
        item.companyUserId = "";
        item.sort = index;
        item.input = false;
        item.checkbox = false;
        item.type = 2;
        item.signatureType = item.signatureType;
      }
    });
  });

  return list;
}

// 格式化签章
function signaturesFilterOne(list) {
  list.map((item, index) => {
    if (item.signatureType == 0) {
      item.disabled = true;
      item.leable = "激励对象签字";
      item.companyUserId = item.companyUserId;
      item.sort = index;
      item.input = false;
      item.checkbox = false;
      item.type = 2;
      item.signatureType = item.signatureType;
    }
    if (item.signatureType == 1) {
      item.disabled = true;
      item.leable = "出让方签字";
      item.companyUserId = item.companyUserId;
      item.sort = index;
      item.input = false;
      item.checkbox = false;
      item.type = 2;
      item.signatureType = item.signatureType;
    }
    if (item.signatureType == 2) {
      item.disabled = true;
      item.leable = "受让方签字";
      item.companyUserId = item.companyUserId;
      item.sort = index;
      item.input = false;
      item.checkbox = false;
      item.type = 2;
      item.signatureType = item.signatureType;
    }

    if (item.signatureType == 3) {
      item.disabled = item.companyUserId != "0" ? true : false;
      item.leable = "授权代表签字";
      item.companyUserId = item.companyUserId == "0" ? "" : item.companyUserId;
      item.sort = index;
      item.input = true;
      item.checkbox = true;
      item.type = 2;
      item.signatureType = item.signatureType;
    }
    if (item.signatureType == 4) {
      item.disabled = item.companyUserId != "0" ? true : false;
      item.leable = "公司盖章";
      item.companyUserId = item.companyUserId == "0" ? "" : item.companyUserId;
      item.sort = index;
      item.input = true;
      item.checkbox = true;
      item.type = 1;
      item.signatureType = item.signatureType;
    }
    if (item.signatureType == 5) {
      item.disabled = true;
      item.leable = "被回购方";
      item.companyUserId = item.companyUserId == "0" ? "" : item.companyUserId;
      item.sort = index;
      item.input = false;
      item.checkbox = false;
      item.type = 2;
      item.signatureType = item.signatureType;
    }
    if (item.signatureType == 6) {
      item.disabled = true;
      item.leable = "回购方";
      item.companyUserId = item.companyUserId == "0" ? "" : item.companyUserId;
      item.sort = index;
      item.input = false;
      item.checkbox = false;
      item.type = 2;
      item.signatureType = item.signatureType;
    }
  });
  return list;
}

// 过滤签章 删除disabled 等于false
function signaturesSubmitOne(data) {
  let arr = JSON.parse(JSON.stringify(data));
  arr.map((item, i) => {
    if (item.disabled == false) {
      arr.splice(i, i);
    }
  });
  console.log(11111111111, arr);
  return arr;
}

function cloneObject(obj) {
  var newObj = {}; //如果不是引用类型，直接返回
  if (typeof obj !== "object") {
    return obj;
  }
  //如果是引用类型，遍历属性
  else {
    for (var attr in obj) {
      //如果某个属性还是引用类型，递归调用
      newObj[attr] = cloneObject(obj[attr]);
    }
  }
  return newObj;
}

// 过滤签章 删除disabled 等于false
function signaturesSubmit(data) {
  let arr = JSON.parse(JSON.stringify(data));
  arr.map((items, index) => {
    items.planSignatures.map((item, i) => {
      // if (item.disabled == false) {
      //   items.planSignatures.splice(i, i);
      // }
    });
  });
  return arr;
}

function disabledDate(current) {
  return current && current > moment().endOf("day");
}

// 文件下载
function dowloadFile(data, fileName) {
  // 创建当前时间字符串，生成文件名称时使用
  // const time = +new Date()
  if (!fileName) {
    let dis = data.headers["content-disposition"];
    fileName = decodeURIComponent(dis.split("attachment;filename=")[1]);
  }
  // 转化为blob对象
  const blob = new Blob([data.data || data], {
    type: "application/octet-stream"
  });

  const urlObject = window.URL || window.webkitURL || window;
  // 将blob对象转为一个URL
  let blobURL = urlObject.createObjectURL(blob);
  // 创建一个a标签
  let tempLink = document.createElement("a");
  // 隐藏a标签
  tempLink.style.display = "none";
  // 设置a标签的href属性为blob对象转化的URL
  tempLink.href = blobURL;
  // 给a标签添加下载属性
  tempLink.setAttribute("download", fileName);
  if (typeof tempLink.download === "undefined") {
    tempLink.setAttribute("target", "_blank");
  }
  // 将a标签添加到body当中
  document.body.appendChild(tempLink);
  // 启动下载
  tempLink.click();
  // 下载完毕删除a标签
  document.body.removeChild(tempLink);
  urlObject.revokeObjectURL(blobURL);
}

//获取当前时间
function currentDate() {
  let date = new Date().getTime();
  let time = formatTime.formatTime(date, "yyyy-MM-dd");
  // let time = formatTime.formatTime(date, "yyyy-MM-dd 00:00:00");
  return time;
}

function kyc(url,fullPath){
  let obj = {
    url:url,
    callback:fullPath?fullPath:router.fullPath
  }
  store.commit('SET_KYC',obj)
  router.push(`/kyc}`)

}

export {
  debounce,
  treeBuild,
  treeBuildS,
  findLeafs,
  getFormatDate,
  randomStr,
  filterDate,
  stringDate,
  treeBuildRouter,
  passwordLevel,
  fileFilter,
  fileDetail,
  signaturesFilter,
  signaturesFilterOne,
  signaturesSubmitOne,
  cloneObject,
  signaturesSubmit,
  disabledDate,
  dowloadFile,
  currentDate,
  kyc
};
